<script src="https://unpkg.com/deeplearn"></script>
<script src="dist/bundle.js"></script>

<h2>Training images</h2>
<img id="cat" src="images/cat.jpg"></img>
<img id="dog1" src="images/dog1.jpg"></img>
<h2>Input image</h2>
<img id="dog2"  src="images/dog2.jpg"></img>
<div id="result"></div>

<script>
  const cat = document.getElementById('cat');
  const dog1 = document.getElementById('dog1');
  const dog2 = document.getElementById('dog2');
  const resultElement = document.getElementById('result');

  window.onload = async () => {
    resultElement.innerText = 'Loading classifier...';

    // If dl isn't loaded, wait 1 second.
    if (dl == null) {
      await new Promise(resolve => setTimeout(resolve, 1000));
    }

    const knn = new knn_image_classifier.KNNImageClassifier(2, 1);
    await knn.load();

    resultElement.innerText = 'Training...';

    const catPixels = dl.fromPixels(cat);
    const dog1Pixels = dl.fromPixels(dog1);
    const dog2Pixels = dl.fromPixels(dog2);

    knn.addImage(catPixels, 0);
    knn.addImage(dog1Pixels, 1);

    resultElement.innerText = 'Predicting...';

    const prediction = await knn.predictClass(dog2Pixels);

    resultElement.innerText = 'Predicted to be class '+(prediction.classIndex+1);
  };

</script>
